package com.rk.kbk.controller;

import com.rk.kbk.common.JsonResp;
import com.rk.kbk.controller.config.Config;
import com.rk.kbk.controller.enums.FileType;
import com.rk.kbk.dao.VersionDao;
import com.rk.kbk.model.Version;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * Created by bilibili on 2017/5/15.
 */
@CrossOrigin
@RestController
@Transactional
@RequestMapping(value="/api/version")
public class VersionController {
    private Logger log = Logger.getLogger(this.getClass());
    @Autowired
    private VersionDao versionDao;
    @Autowired
    public Config config;
    /**
     * @获取当前版本
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/findCurrentVersion",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findCurrentVersion(Integer type){
        log.debug("获取当前版本");
        List<Version> versions=versionDao.findByStatusAndTypeOrderByGmtDatetimeDesc(1,type);
        if(!versions.isEmpty()){
            return JsonResp.ok(versions.get(0));
        }else {
            return  JsonResp.fa("当前已是最新版本");
        }

    }


    /**
     * @上传当前最新版本
     * @param
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/upLoadCurrentVersion",
            method = RequestMethod.POST,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public ModelAndView upLoadCurrentVersion(String name, @RequestParam("file") CommonsMultipartFile file, HttpServletRequest request){
        log.debug("上传当前最新版本");
        Version version=new Version();
        version.setStatus(1);
        version.setVersionCode(name);
        String select=request.getParameter("userType");
        version.setType(Integer.valueOf(select));
        String[] paths = FileType.getPath(FileType.OTHER, 1,request);
        // 获取文件的后缀
        String suffix;
        try {
            suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
        } catch (Exception e) {
            suffix = "";
        }

        String fileName = UUID.randomUUID().toString();
        fileName += suffix;
        String path=paths[0] + File.separator + fileName;
        File saveFile = new File(path);
        try {
            file.transferTo(saveFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
        StringBuffer  url=request.getRequestURL();
        String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString();
     /*    String savePath=path.split("/")[1];
        version.setLink(tempContextUrl+savePath.replace("\\","/"))*/;
        String savePath = config.getUploadHost(request, null, saveFile.getParentFile().getName(), saveFile.getName());
        version.setLink(savePath);
        versionDao.save(version);
        String backUrl=tempContextUrl.split("interface/")[0]+"admin/version_list.html";
       return new ModelAndView("redirect:"+backUrl);
        //return  "redirect:http://127.0.0.1:8020/kbk_admin/version_list.html";
    }

    /**
     * @获取版本列表
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/versionList",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp findversionList() {
        log.debug("获取商品详情-ByGoodsId");
        List<Version> versions=versionDao.findAll();
        return JsonResp.ok(versions);
    }

    /**
     * @废弃版本
     * @param id
     * @return 返回值JsonResp
     */
    @RequestMapping(value = "/deleteVersionOne",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
    public JsonResp deleteVersionOne(Long id) {
        log.debug("废弃版本");
        Version version =versionDao.findOne(id);
        version.setStatus(2);
        return JsonResp.ok();
    }
}
